﻿using System.IO.IsolatedStorage;
using System.IO;
using System.Xml.Serialization;

namespace Kiva7.DataClasses
{
    public class FriendFile
    {
        const string DataDirectory = "Data";
        const string DataFile = @"Data\FriendList.xml";

        public static FriendFile Load()
        {
            try
            {
                IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();

                if (!file.DirectoryExists(DataDirectory))
                {
                    file.CreateDirectory(DataDirectory);
                }

                using (IsolatedStorageFileStream stream 
                    = file.OpenFile(DataFile, FileMode.Open, FileAccess.Read,
                                                     FileShare.Read))
                {
                    XmlSerializer xs = new XmlSerializer(typeof (FriendFile));

                    return xs.Deserialize(stream) as FriendFile;
                }
            }
            catch
            {
                return new FriendFile();
            }
        }

        public void Save()
        {
            try
            {
                IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();

                if (!file.DirectoryExists(DataDirectory))
                {
                    file.CreateDirectory(DataDirectory);
                }

                using (IsolatedStorageFileStream stream 
                    = file.CreateFile(DataFile))
                {
                    XmlSerializer xs = new XmlSerializer(typeof (FriendFile));

                    xs.Serialize(stream, this);
                }
            }
            catch
            {
            }
        }

        public FriendFile()
        {
            _Friends = new FriendList(); 
        }

        public FriendFile(FriendList friends)
        {
            this._Friends = friends;
        }

        private FriendList _Friends;
        public FriendList Friends 
        {
            get
            {
                return _Friends;
            }
        }
    }
}
